package map.gui.config;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;

import map.tools.interactions.DeviceActionTable;
import map.tools.interactions.WidgetBehaviorTable;
import map.tools.plateform.MappingTableSerializer;
import map.tools.plateform.PlateformSerializer;
import map.tools.uimodel.WidgetsModelsSerializer;
import uimigration.Plateform.Device;
import uimigration.WidgetsModel.APIModel;
import uimigration.mappingmodel.MappingTable;

public class MappingTables extends JFrame {

	private static final long serialVersionUID = 1L;
	public static final String XMLFILESPATH=".//models//xml//";  //  @jve:decl-index=0:
	public static final String APIFILESPATH=".//models//api//";  //  @jve:decl-index=0:
	public static final String DEVICEFILESPATH=".//models//device//";  //  @jve:decl-index=0:
	public static final String TABLEFILESPATH=".//models//tables//";  //  @jve:decl-index=0:
//
	private JPanel jContentPane = null;
	private JTabbedPane jTabbedPane = null;
	private JPanel jPanelDeviceModel = null;
	private JPanel jPanelWidgets = null;
	private JLabel jLabelAPIModelWidgets = null;
	private JComboBox jComboBoxAPIDevice = null;
	private JScrollPane jScrollPaneDevice = null;
	private JTable jTableDeviceAction = null;
	private JButton jButtonSaveDevices = null;
	private JButton jButtonCancel = null;
	private JLabel jLabelWidgets = null;
	private JComboBox jComboBoxAPIWidgets = null;
	private JScrollPane jScrollPaneWidgets = null;
	private JTable jTableWidgetsBehaviors = null;
	private JButton jButtonSaveWidgets = null;
	private JButton jButtonCancelWidgets = null;
	public static HashMap<String,APIModel> apimodel=null;
	public static HashMap<String ,MappingTable> mapping= null;
	public static List<Device> devices=null;

	/**
	 * This is the default constructor
	 */
	public MappingTables() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(700, 500);
		this.setLocation(new Point(320, 320));
		this.setResizable(false);
		this.setContentPane(getJContentPane());
		this.setTitle("Mapping Configurations");
		this.setVisible(true);
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent e) {
				File dir= new File(APIFILESPATH);
				if(dir.isDirectory())
				{
					File f[]=dir.listFiles();
						for(File i:f){
						if(i.canRead() &&! i.isHidden()){
							jComboBoxAPIWidgets.addItem(i);
							jComboBoxAPIDevice.addItem(i);
						}
					}
				}
				dir= new File(DEVICEFILESPATH);
				if(dir.isDirectory())
				{
					File f[]=dir.listFiles();
						for(File i:f){
						if(i.canRead() &&! i.isHidden()){
							try
							{
								Device dev=new PlateformSerializer().loadDevice(i);
								if(dev!=null )
								{
									if(devices==null)
										devices= new ArrayList<Device>();
									devices.add(dev);
								}
							}catch(Exception e1)
							{
								e1.printStackTrace();
							}
						}
					}
				}

			}
		});
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJTabbedPane(), BorderLayout.CENTER);
			jContentPane.setVisible(true);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jTabbedPane	
	 * 	
	 * @return javax.swing.JTabbedPane	
	 */
	private JTabbedPane getJTabbedPane() {
		if (jTabbedPane == null) {
			jTabbedPane = new JTabbedPane();
			jTabbedPane.addTab("Devices", null, getJPanelDeviceModel(), "Set the devices events abstract actions");
			jTabbedPane.addTab("Widgets", null, getJPanelWidgets(), "Set the widgets behaviors");
		}
		return jTabbedPane;
	}

	/**
	 * This method initializes jPanelDeviceModel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelDeviceModel() {
		if (jPanelDeviceModel == null) {
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.gridx = 2;
			gridBagConstraints4.gridwidth = 3;
			gridBagConstraints4.gridy = 2;
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 1;
			gridBagConstraints3.gridheight = 1;
			gridBagConstraints3.gridy = 2;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.fill = GridBagConstraints.BOTH;
			gridBagConstraints2.gridy = 1;
			gridBagConstraints2.weightx = 3.0D;
			gridBagConstraints2.weighty = 1.0D;
			gridBagConstraints2.gridwidth = 3;
			gridBagConstraints2.gridx = 0;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints1.gridy = 0;
			gridBagConstraints1.weightx = 1.0;
			gridBagConstraints1.gridx = 2;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.gridy = 0;
			jLabelAPIModelWidgets = new JLabel();
			jLabelAPIModelWidgets.setText("API Model");
			jLabelAPIModelWidgets.setVerticalAlignment(SwingConstants.TOP);
			jLabelAPIModelWidgets.setVerticalTextPosition(SwingConstants.TOP);
			jPanelDeviceModel = new JPanel();
			jPanelDeviceModel.setLayout(new GridBagLayout());
			jPanelDeviceModel.setName("Devices");
			jPanelDeviceModel.add(jLabelAPIModelWidgets, gridBagConstraints);
			jPanelDeviceModel.add(getJComboBoxAPIDevice(), gridBagConstraints1);
			jPanelDeviceModel.add(getJScrollPaneDevice(), gridBagConstraints2);
			jPanelDeviceModel.add(getJButtonSaveDevices(), gridBagConstraints3);
			jPanelDeviceModel.add(getJButtonCancel(), gridBagConstraints4);
		}
		return jPanelDeviceModel;
	}

	/**
	 * This method initializes jPanelWidgets	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelWidgets() {
		if (jPanelWidgets == null) {
			GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.gridx = 2;
			gridBagConstraints9.gridwidth = 3;
			gridBagConstraints9.gridy = 2;
			GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
			gridBagConstraints8.gridx = 1;
			gridBagConstraints8.gridy = 2;
			GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
			gridBagConstraints7.fill = GridBagConstraints.BOTH;
			gridBagConstraints7.gridy = 1;
			gridBagConstraints7.weightx = 3.0D;
			gridBagConstraints7.weighty = 1.0;
			gridBagConstraints7.gridwidth = 3;
			gridBagConstraints7.gridx = 0;
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints6.gridy = 0;
			gridBagConstraints6.weightx = 1.0;
			gridBagConstraints6.gridx = 2;
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.gridx = 0;
			gridBagConstraints5.gridy = 0;
			jLabelWidgets = new JLabel();
			jLabelWidgets.setText("API Model");
			jLabelWidgets.setVerticalTextPosition(SwingConstants.TOP);
			jLabelWidgets.setVerticalAlignment(SwingConstants.TOP);
			jPanelWidgets = new JPanel();
			jPanelWidgets.setLayout(new GridBagLayout());
			jPanelWidgets.add(jLabelWidgets, gridBagConstraints5);
			jPanelWidgets.add(getJComboBoxAPIWidgets(), gridBagConstraints6);
			jPanelWidgets.add(getJScrollPaneWidgets(), gridBagConstraints7);
			jPanelWidgets.add(getJButtonSaveWidgets(), gridBagConstraints8);
			jPanelWidgets.add(getJButtonCancelWidgets(), gridBagConstraints9);
		}
		return jPanelWidgets;
	}

	/**
	 * This method initializes jComboBoxAPIDevice	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBoxAPIDevice() {
		if (jComboBoxAPIDevice == null) {
			jComboBoxAPIDevice = new JComboBox();
			jComboBoxAPIDevice.addItemListener(new java.awt.event.ItemListener() {
				public void itemStateChanged(java.awt.event.ItemEvent e) {
					if(apimodel==null && mapping==null){
						apimodel= new HashMap<String,APIModel>();
						mapping=new HashMap<String,MappingTable>();
						APIModel api=new WidgetsModelsSerializer().load(((File)jComboBoxAPIDevice.getSelectedItem()));
						MappingTable map= new MappingTableSerializer().load(( new File(TABLEFILESPATH+"MappingTable.xmi")));
						apimodel.put(e.getItem().toString(), api);
						mapping.put(e.getItem().toString(),map);
					}
					else if (!apimodel.containsKey(e.getItem().toString()))
					{
						APIModel api=new WidgetsModelsSerializer().load(((File)jComboBoxAPIDevice.getSelectedItem()));
						MappingTable map= new MappingTableSerializer().load(( new File(TABLEFILESPATH+"MappingTable.xmi")));
						apimodel.put(e.getItem().toString(), api);
						mapping.put(e.getItem().toString(),map);
						
					}
					jTableDeviceAction=getJTableDeviceAction(apimodel.get(e.getItem().toString()), mapping.get(e.getItem().toString()));

				}
			});
		}
		return jComboBoxAPIDevice;
	}

	/**
	 * This method initializes jScrollPaneDevice	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPaneDevice() {
		if (jScrollPaneDevice == null) {
			jScrollPaneDevice = new JScrollPane();
			jScrollPaneDevice.setViewportView(getJTableDeviceAction());
		}
		return jScrollPaneDevice;
	}

	/**
	 * This method initializes jTableDeviceAction	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTableDeviceAction() {
		if (jTableDeviceAction == null) {
			jTableDeviceAction = new JTable();
			jTableDeviceAction.setModel(new MappingTableModel("Device"));
		}
		return jTableDeviceAction;
	}
	private JTable getJTableDeviceAction(APIModel apimodel, MappingTable mapping) {
		if (jTableDeviceAction == null) {
			jTableDeviceAction.setModel(new MappingTableModel(apimodel,mapping,devices));
		}
		else
			((MappingTableModel)(jTableDeviceAction.getModel())).UpdateData(apimodel, mapping);
		return jTableDeviceAction;
	}


	/**
	 * This method initializes jButtonSaveDevices	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonSaveDevices() {
		if (jButtonSaveDevices == null) {
			jButtonSaveDevices = new JButton();
			jButtonSaveDevices.setText("Save");
		}
		return jButtonSaveDevices;
	}

	/**
	 * This method initializes jButtonCancel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonCancel() {
		if (jButtonCancel == null) {
			jButtonCancel = new JButton();
			jButtonCancel.setText("Cancel");
			jButtonCancel.setMnemonic(KeyEvent.VK_UNDEFINED);
			jButtonCancel.setHorizontalAlignment(SwingConstants.LEFT);
		}
		return jButtonCancel;
	}

	/**
	 * This method initializes jComboBoxAPIWidgets	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBoxAPIWidgets() {
		if (jComboBoxAPIWidgets == null) {
			jComboBoxAPIWidgets = new JComboBox();
			jComboBoxAPIWidgets.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.out.println("actionPerformed()"); 
					
				}
			});
			jComboBoxAPIWidgets.addItemListener(new java.awt.event.ItemListener() {
				public void itemStateChanged(java.awt.event.ItemEvent e) {
					// TODO Auto-generated Event stub itemStateChanged()
					if(apimodel==null && mapping==null){
						apimodel= new HashMap<String,APIModel>();
						mapping=new HashMap<String,MappingTable>();
						APIModel api=new WidgetsModelsSerializer().load(((File)jComboBoxAPIWidgets.getSelectedItem()));
						MappingTable map= new MappingTableSerializer().load(( new File(TABLEFILESPATH+"MappingTable.xmi")));
						apimodel.put(e.getItem().toString(), api);
						mapping.put(e.getItem().toString(),map);
					}
					else if (!apimodel.containsKey(e.getItem().toString()))
					{
						APIModel api=new WidgetsModelsSerializer().load(((File)jComboBoxAPIWidgets.getSelectedItem()));
						MappingTable map= new MappingTableSerializer().load(( new File(TABLEFILESPATH+"MappingTable.xmi")));
						apimodel.put(e.getItem().toString(), api);
						mapping.put(e.getItem().toString(),map);
						
					}
					jTableWidgetsBehaviors=getJTableWidgetsBehaviors(apimodel.get(e.getItem().toString()), mapping.get(e.getItem().toString()));
				}
			});
		}
		return jComboBoxAPIWidgets;
	}

	/**
	 * This method initializes jScrollPaneWidgets	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPaneWidgets() {
		if (jScrollPaneWidgets == null) {
			jScrollPaneWidgets = new JScrollPane();
			jScrollPaneWidgets.setViewportView(getJTableWidgetsBehaviors());
		}
		return jScrollPaneWidgets;
	}

	/**
	 * This method initializes jTableWidgetsBehaviors	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTableWidgetsBehaviors() {
		if (jTableWidgetsBehaviors == null) {
			jTableWidgetsBehaviors = new JTable();
			jTableWidgetsBehaviors.setModel(new MappingTableModel());
		}
		return jTableWidgetsBehaviors;
	}
	private JTable getJTableWidgetsBehaviors(APIModel apimodel, MappingTable mapping) {
		if (jTableWidgetsBehaviors == null) {
			jTableWidgetsBehaviors.setModel(new MappingTableModel(apimodel,mapping));
		}
		else
			((MappingTableModel)jTableWidgetsBehaviors.getModel()).UpdateData(apimodel, mapping);
		return jTableWidgetsBehaviors;
	}

	/**
	 * This method initializes jButtonSaveWidgets	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonSaveWidgets() {
		if (jButtonSaveWidgets == null) {
			jButtonSaveWidgets = new JButton();
			jButtonSaveWidgets.setText("Save");
			jButtonSaveWidgets.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return jButtonSaveWidgets;
	}

	/**
	 * This method initializes jButtonCancelWidgets	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonCancelWidgets() {
		if (jButtonCancelWidgets == null) {
			jButtonCancelWidgets = new JButton();
			jButtonCancelWidgets.setText("Cancel");
			jButtonCancelWidgets.setHorizontalAlignment(SwingConstants.LEFT);
			jButtonCancelWidgets.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					System.exit(DO_NOTHING_ON_CLOSE);
				}
			});
		}
		return jButtonCancelWidgets;
	}

}
class MappingTableModel extends AbstractTableModel {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] columnNames = {"Event",
                                    "Render",
                                    "Content",
                                    "Link"};
    private Object[][] dataD ={};
    private Object[][] dataW ={};
    private String tableType="Widget";
    
    public MappingTableModel(WidgetBehaviorTable wtable){
    	dataW=wtable.getData();
    }
    public MappingTableModel(DeviceActionTable dtable){
    	columnNames = new String[] {"Device", "Event", "Activate","MoveDevice","EnterData"};
    	dataD=dtable.getData();
    	tableType="Device";
    }

    public MappingTableModel(){
    	
    	dataW= new Object[2][4];
    	dataD= new Object[2][5];
    }
    public MappingTableModel(String device){
    	columnNames = new String[] {"Device", "Event", "Activate","MoveDevice","EnterData"};
    	dataD= new Object[2][5];
    	tableType="Device";
    }

    public MappingTableModel(APIModel apimodel,MappingTable maping,List<Device> ld){
    	if(ld!=null)
    		this.tableType="Device";
    	if(tableType.equals("Widget"))
    		dataW=new WidgetBehaviorTable(maping).getData();
    	else
    	{	columnNames = new String[] {"Device", "Event", "Activate","MoveDevice","EnterData"};
    		dataD= new DeviceActionTable(apimodel,maping,ld).getData();
    		tableType="Device";
    	}
    }

    public MappingTableModel(APIModel apimodel,MappingTable maping){
    	dataW=new WidgetBehaviorTable(maping).getData();
    }

    public void UpdateData(APIModel apimodel,MappingTable maping)
    {
    	WidgetBehaviorTable wtable=new WidgetBehaviorTable(maping);
    	dataW=wtable.getData();
    	fireTableDataChanged();
    	
    }
    public void UpdateData(APIModel apimodel,MappingTable maping,Device d)
    {

    	dataD=new DeviceActionTable(apimodel,maping,d).getData();
    	fireTableDataChanged();
    	
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
    	if(tableType.contains("Device"))
    	{	if(dataD!=null)
	    		return dataD.length;
	    	else 
	    		return 0;
    	}
    	else
    	{	if(dataW!=null)
    		return dataW.length;
    	else 
    		return 0;	
    	}
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
    	if(tableType.contains("Device"))
    		return dataD[row][col];
    	else
    		return dataW[row][col];
    }

     /*
     * Don't need to implement this method unless your table's
     * editable.
     */
    public boolean isCellEditable(int row, int col) {
        //Note that the data/cell address is constant,
        //no matter where the cell appears onscreen.
        if (col < 2) {
            return false;
        } else {
            return true;
        }
    }

}
